<script lang="jsx" setup>
import { computed, ref } from 'vue';
import { CheckOutlined, DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import {
  addFormServiceRecord,
  completeFormServiceRecord,
  deleteFormServiceRecord,
  getModuleSelect,
  getSystemSelect,
  updateFormServiceRecord
} from '@/service/api/modules/manage/form-service-record';

const systemList = ref([]);
const moduleList = ref([]);
const searchParams = ref({
  formName: null,
  system: null,
  module: null,
  time: null
});
const formList = [
  {
    type: 'input',
    key: 'formName',
    label: '表单名称',
    placeholder: '请输入表单名称',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4
  },
  {
    type: 'select',
    key: 'system',
    label: '系统',
    placeholder: '请选择系统',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    selectOptions: systemList,
    change: () => {
      const sysId = systemList.value.find(item => item.value === searchParams.value.system)?.id;
      moduleList.value = [];
      getModuleList(sysId, list => {
        moduleList.value = list;
      });
    }
  },
  {
    type: 'select',
    key: 'module',
    label: '模块',
    placeholder: '请选择模块',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    selectOptions: moduleList
  },
  {
    type: 'select',
    key: 'state',
    label: '状态',
    placeholder: '请选择状态',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    selectOptions: [
      { label: '未完成', value: 0 },
      { label: '已完成', value: 1 }
    ]
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '日期',
    showTime: true,
    span: 24,
    md: 12,
    lg: 10,
    xl: 8,
    xxl: 6
  }
];

function getSystemList() {
  getSystemSelect().then(({ data, error }) => {
    console.log(data);
    systemList.value = data?.map(item => {
      return {
        ...item,
        label: item.system,
        value: item.system
      };
    });
  });
}
getSystemList();

function getModuleList(sysId, cb) {
  getModuleSelect(sysId).then(({ data, error }) => {
    console.log(data);
    const list = data?.map(item => {
      return {
        ...item,
        label: item.module,
        value: item.module
      };
    });

    cb && cb(list);
  });
}

const searchData = computed(() => {
  const params = {
    ...searchParams.value
  };
  if (searchParams.value?.time?.[0]) {
    params.startTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD');
    params.endTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD');
  }
  delete params.time;
  return params;
});

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'system',
    dataIndex: 'system',
    title: '系统',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'module',
    dataIndex: 'module',
    title: '模块',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'formName',
    dataIndex: 'formName',
    title: '表单名称',
    align: 'center',
    width: 180,
    checked: true,
    ellipsis: true
  },
  {
    key: 'state',
    dataIndex: 'state',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <span class={record.state === 0 ? 'text-red-500' : 'text-green-500'}>{['未完成', '已完成'][record.state]}</span>
      );
    }
  },
  {
    key: 'oaCountersignTime',
    dataIndex: 'oaCountersignTime',
    title: 'OA会签时间',
    align: 'center',
    width: 160,
    checked: true,
    ellipsis: true
  },
  {
    key: 'completionTime',
    dataIndex: 'completionTime',
    title: '完成时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'elapsedTime',
    dataIndex: 'elapsedTime',
    title: '耗时',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'operator',
    dataIndex: 'operator',
    title: '创建人',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    align: 'center',
    checked: true,
    width: 160,
    ellipsis: true,
    customRender: ({ record }) => {
      return dayjs(record.createDate).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'updateUser',
    dataIndex: 'updateUser',
    title: '修改人',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '修改时间',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return dayjs(record.updateDate).format('YYYY-MM-DD HH:mm:ss');
    }
  }
];

const tableRef = ref(null);

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      formName: null,
      system: null,
      module: null,
      time: null
    };
    search();
  });
}

const selectList = ref([]);
function handleTableSelectChange(val) {
  selectList.value = val;
}

const formModuleList = ref([]);
const operationType = ref('add');
const { handleClose, handleLoading, handleShow, updateModalOptions } = window.$useModal({
  modalOption: {
    title: '新增',
    width: '600px',
    destroyOnClose: true
  },
  formData: {
    system: null,
    module: null,
    formName: null,
    oaCountersignTime: null,
    remark: null
  },
  formList: [
    {
      type: 'select',
      key: 'system',
      label: '系统',
      placeholder: '请选择系统',
      span: 24,
      selectOptions: systemList,
      change: val => {
        const sysId = systemList.value.find(item => item.value === val)?.id;
        formModuleList.value = [];
        getModuleList(sysId, list => {
          formModuleList.value = list;
        });
      }
    },
    {
      type: 'select',
      key: 'module',
      label: '模块',
      placeholder: '请选择模块',
      span: 24,
      selectOptions: formModuleList
    },
    {
      type: 'input',
      key: 'formName',
      label: '表单名称',
      placeholder: '请输入表单名称',
      span: 24
    },
    {
      type: 'datePicker',
      key: 'oaCountersignTime',
      label: 'OA会签时间',
      placeholder: '请输入OA会签时间',
      showTime: true,
      span: 24
    },
    {
      type: 'textarea',
      key: 'remark',
      label: '表单名称',
      placeholder: '请输入表单名称',
      span: 24
    }
  ],
  onOk: formData => {
    let pro;
    if (operationType.value === 'add') {
      pro = addFormServiceRecord(formData);
    } else {
      pro = updateFormServiceRecord(formData);
    }
    handleLoading(true);
    pro
      .then(({ error }) => {
        if (!error) {
          window.$message.success('操作成功!');
          search();
          handleClose();
        }
      })
      .finally(() => {
        handleLoading(false);
        selectList.value = [];
      });
  },
  onClose: () => {
    formModuleList.value = [];
  }
});

function handleAdd(type) {
  operationType.value = type;
  if (type === 'add') {
    handleShow({ system: null, module: null, formName: null, oaCountersignTime: null, remark: null });
    updateModalOptions({
      title: '新增表单服务记录'
    });
  } else {
    handleShow(selectList.value[0]);
    updateModalOptions({
      title: '修改表单服务记录'
    });
  }
}

function handleDelete() {
  if (selectList.value.length === 0) {
    window.$message.error('请选择要删除的记录');
    return;
  }
  window.$modal.confirm({
    title: '确认删除所选择的记录吗?',
    onOk: () => {
      deleteFormServiceRecord(selectList.value).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功!');
          search();
          selectList.value = [];
        }
      });
    },
    onCancel: () => {}
  });
}

function handleSuccess() {
  if (selectList.value.length === 0) {
    window.$message.error('请选择要完成的记录');
    return;
  }
  window.$modal.confirm({
    title: '确认完成所选择的记录吗?',
    onOk: () => {
      completeFormServiceRecord(selectList.value).then(({ error }) => {
        if (!error) {
          window.$message.success('操作成功!');
          search();
          selectList.value = [];
        }
      });
    },
    onCancel: () => {}
  });
}
</script>

<template>
  <div class="jl-main-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      v-model:searchParams="searchParams"
      :form-list="formList"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      ref="tableRef"
      v-model:searchParams="searchData"
      :column="column"
      auto-generate-uuid
      :scroll="{ y: 'auto' }"
      is-init-get-data
      url="/mes/formModification/list"
      @table-select-change="handleTableSelectChange"
    >
      <template #title>
        <AButton type="primary" ghost class="mini-btn mr-8px" @click="handleAdd('add')">
          <PlusOutlined class="align-sub text-size-18px" />
          <span class="ml-3px">新增</span>
        </AButton>

        <AButton
          type="primary"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectList.length !== 1"
          @click="handleAdd('edit')"
        >
          <EditOutlined class="align-sub text-size-18px" />
          <span class="ml-3px">修改</span>
        </AButton>

        <AButton
          type="primary"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectList.length === 0"
          @click="handleSuccess"
        >
          <CheckOutlined class="align-sub text-size-18px" />
          <span class="ml-3px">批量完成</span>
        </AButton>

        <AButton
          type="primary"
          danger
          ghost
          class="mini-btn mr-8px"
          :disabled="selectList.length === 0"
          @click="handleDelete"
        >
          <DeleteOutlined class="align-sub text-size-18px" />
          <span class="ml-3px">批量删除</span>
        </AButton>
      </template>
    </Table>
  </div>
</template>

<style lang="scss" scoped></style>
